using System;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.ComponentModel;

namespace GoodStuff.Web.Controls
{
	/// <summary>
	/// Summary description for ProgressBar.
	/// </summary>
	[DefaultProperty("Value")]
	public class ProgressBar : WebControl
	{
		public ProgressBar()
		{
			this.BorderColor = Color.Black;
			this.BorderStyle = BorderStyle.Solid;
			this.BorderWidth = Unit.Pixel(1);
			this.ForeColor = Color.White;
		}

		protected override HtmlTextWriterTag TagKey
		{
			get
			{
				return HtmlTextWriterTag.Div;
			}
		}

		[DefaultValue("Black")]
		public Color BarColor
		{
			get
			{
				object o = ViewState["BarColor"];
				if(o is Color)
					return (Color)o;
				return Color.Black;
			}
			set
			{
				ViewState["BarColor"] = value;
			}
		}

		public string Text
		{
			get
			{
				object o = ViewState["Text"];
				if(o is string)
					return (string)o;
				return null;
			}
			set
			{
				ViewState["Text"] = value;
			}
		}


		[DefaultValue(0)]
		public int MinValue
		{
			get
			{
				object o = ViewState["MinValue"];
				if(o is int)
					return (int)o;
				return 0;
			}
			set
			{
				ViewState["MinValue"] = value;
			}
		}

		[DefaultValue(100)]
		public int MaxValue
		{
			get
			{
				object o = ViewState["MaxValue"];
				if(o is int)
					return (int)o;
				return 100;
			}
			set
			{
				ViewState["MaxValue"] = value;
			}
		}

		[DefaultValue(0)]
		public int Value
		{
			get
			{
				object o = ViewState["Value"];
				if(o is int)
					return (int)o;
				return 0;
			}
			set
			{
				ViewState["Value"] = value;
			}
		}

		public int Percentage
		{
			get
			{
				return (Value * 100) / (MaxValue - MinValue);
			}
		}

		/// <summary>
		/// A clientside ID that can be used to retrieve/set the value by scripting.
		/// </summary>
		public string ClientValueID
		{
			get
			{
				return this.ClientID + "bar";
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			this.Style.Add("padding", "2px");
			base.OnPreRender (e);
		}

		protected override void RenderChildren(HtmlTextWriter writer)
		{
			writer.AddStyleAttribute("width", string.Format("{0}%", Percentage));
			writer.AddStyleAttribute("background-color", BarColor.Name);
			writer.AddStyleAttribute("white-space", "nowrap");
			writer.AddStyleAttribute("color", ForeColor.Name);		
			writer.AddStyleAttribute("overflow", "hidden");
			writer.AddAttribute("id", ClientValueID);
			writer.RenderBeginTag("div");
			writer.Write(Text);
			writer.RenderEndTag();
		}
	}
}
